import { View, Text, StyleSheet, Image, TouchableOpacity } from "react-native"
import React, { useState } from "react"
import { colors, typography } from "app/theme"
import { useAppSelector } from "app/redux/hooks"
import { scale } from "react-native-size-matters"
import LogoutMenu from "./LogoutMenu"
import AsyncStorage from "@react-native-async-storage/async-storage"
import { useDispatch } from "react-redux"
import { setLogout } from "app/redux/slices/authSlice"

const MainHeader = () => {
  const dispatch=useDispatch()
  const providerState = useAppSelector((state) => state?.provider)

  const [expanded, setExpanded] = useState(null)

  const logout=async()=>{
    await AsyncStorage.setItem("email", '')
    await AsyncStorage.setItem("token", '')}

  return (
    <View style={styles.container}>
      <View style={styles.row}>
        <Image
          source={require("../../assets/images/ethera_logo.png")}
          style={styles.logo}
          resizeMode="contain"
        />
        <Text style={styles.text}>ethera</Text>
      </View>
      <View>
        <TouchableOpacity onPress={() => setExpanded(!expanded)}>
          <Image
            source={
              providerState?.provider?.avatar
                ? { uri: providerState?.provider?.avatar }
                : require("../../assets/images/cr-logo.png")
            }
            style={styles.logo}
            resizeMode="cover"
          />
        </TouchableOpacity>
        {expanded && (
          <LogoutMenu
            expanded={expanded}
            onButtonPress={() => {
              setExpanded(false)
              logout().then(()=>{
                dispatch(setLogout())
              })
            }}
          />
        )}
      </View>
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: colors.lightGrey,
    height: scale(75),
    borderBottomLeftRadius: 20,
    borderBottomRightRadius: 20,
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 20,
  },
  logo: {
    height: scale(40),
    width: scale(40),
    borderRadius: 50,
  },
  text: {
    color: colors.black,
    fontSize: scale(16),
    fontFamily: typography.fonts.spaceGrotesk.semiBold,
    marginLeft: 10,
  },
  row: {
    flexDirection: "row",
    alignItems: "center",
  },
})

export default MainHeader
